import router from './router'
import { useUserStore } from "@/store/modules/user.js";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
// import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })
const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  const store = useUserStore();

  // start progress bar
  NProgress.start()


  const hasToken = getToken()
  // next()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const hasGetUserInfo = store.username
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          await store.getUserInfo().then(() => {
            next({ ...to, replace: true })
          })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.resetToken()
          // Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})



